import router from "./router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { Message } from "element-ui";
import { Route } from "vue-router";
import { UserModule } from "@/store/modules/user";
import { glbVariables } from "@/utils/Utils";
NProgress.configure({ showSpinner: false });

const whiteList = ["/login", "/pathPage"];

router.beforeEach(async (to: Route, _: Route, next: any) => {
  // Start progress bar
  NProgress.start();
  // if (!whiteList.includes(to.path)) {
  //   let pathInfo = { name: to.name, path: to.path, fullPath: to.fullPath, title: to.meta?.title, isActive: true };
  //   glbVariables.tagLs.forEach((it: any) => {
  //     it.isActive = false;
  //   });
  //   var existsObjs = glbVariables.tagLs.filter((it: any) => it.path == to.path);
  //   if (existsObjs.length > 0) {
  //     existsObjs = existsObjs[0];
  //     existsObjs.fullPath = to.fullPath;
  //     existsObjs.isActive = true;
  //   } else {
  //     glbVariables.tagLs.push(pathInfo);
  //   }
  // }

  next();

  NProgress.done();
  //Determine whether the user has logged in
  if (UserModule.token) {
    if (to.path === "/login") {
      // If is logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done();
    } else {
      // Check whether the user has obtained his permission roles
      if (UserModule.roles.length === 0) {
        try {
          // Get user info, including roles
          await UserModule.GetUserInfo();
          // Set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true });
        } catch (err: any) {
          // Remove token and redirect to login page
          UserModule.ResetToken();
          Message.error(err || "Has Error");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      } else {
        next();
      }
    }
  } else {
    // Has no token
    if (whiteList.indexOf(to.path) !== -1) {
      // In the free login whitelist, go directly
      next();
    } else {
      const reg = new RegExp("(clinicalpathway/evaluate2)|(sys/ops)");
      // Other pages that do not have permission to access are redirected to the login page.
      if (reg.test(to.path)) {
        next();
        return;
      }
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach((to: Route) => {
  // Finish progress bar
  NProgress.done();

  // set page title
  document.title = to.meta.title;
});
